package com.jyy.prefabricated.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jyy.prefabricated.entity.*;
import com.jyy.prefabricated.mapper.*;
import com.jyy.prefabricated.utils.DateUtils;
import com.jyy.prefabricated.vo.CoursePackageQuizVo;
import com.jyy.prefabricated.vo.StudentExamVo;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class MyResourceService {

    @Resource
    private CourseMapper courseMapper;

    @Resource
    private ProjectInfoMapper projectInfoMapper;

    @Resource
    private StudentCoursePackageMapper studentCoursePackageMapper;

    @Resource
    private CoursePackageMapper coursePackageMapper;

    @Resource
    private ExamMapper examMapper;

    @Resource
    private CourseCategoryExamMapper courseCategoryExamDao;

    @Resource
    private StudentQuizService studentQuizService;

    @Resource
    private OrderInfoMapper orderInfoMapper;


    /**
     * 查询学员购买的所有项目
     *
     * @param projectName
     * @param studentId
     * @return
     */
    public List<ProjectInfo> selectByProjectNameAndStudentId(String projectName, Integer studentId) {
        return projectInfoMapper.selectByProjectNameAndStudentId(projectName, studentId);
    }

    /**
     * 查询学员购买的所有课程id
     *
     * @param studentId
     * @return
     */
    public List<Integer> selectCourseIdsByStudentId(Integer studentId) {
        List<Integer> courseIds = courseMapper.selectCourseIdsByStudentId(studentId);
        List<Integer> packageIds = courseMapper.selectPackageCourseIdsByStudentId(studentId);
        List<Integer> projectIds = courseMapper.selectProjectCourseIdsByStudentId(studentId);
        courseIds.addAll(packageIds);
        courseIds.addAll(projectIds);
        return courseIds;
    }

    /**
     * 查询学员购买的所有课程包id(未过期的)
     *
     * @param studentId
     * @return
     */
    public List<Integer> selectCoursePackageIdsByStudentId(Integer studentId) {
        //查询学员购买的所有课程包id
        List<Integer> packageIds = new ArrayList<>();
        List<StudentCoursePackage> studentCoursePackageList = studentCoursePackageMapper.selectCoursePackageIdsByStudentId(studentId);
        //排除已过期的
        if (studentCoursePackageList != null && studentCoursePackageList.size() > 0) {
            for (StudentCoursePackage item : studentCoursePackageList) {
                if (item.getOrderId() != null) {
                    if (whetherOverdue(item.getOrderId())) {
                        packageIds.add(item.getPackageId());
                    }
                }
            }
        }
        return packageIds;
    }

    //判断商品（课程包）是否过期
    public Boolean whetherOverdue(Integer orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
        if (orderInfo != null && orderInfo.getPayTime() != null) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date currdate = format.parse(orderInfo.getPayTime());
                Calendar ca = Calendar.getInstance();
                ca.setTime(currdate);
                if (orderInfo.getBuyType() != null && orderInfo.getBuyTypeNum() != null) {
                    if (orderInfo.getBuyType() == 0) {
                        ca.add(Calendar.YEAR, orderInfo.getBuyTypeNum());
                    } else if (orderInfo.getBuyType() == 1) {
                        ca.add(Calendar.MONTH, orderInfo.getBuyTypeNum());
                    } else if (orderInfo.getBuyType() == 2) {
                        ca.add(Calendar.WEEK_OF_YEAR, orderInfo.getBuyTypeNum());
                    } else if (orderInfo.getBuyType() == 3) {
                        ca.add(Calendar.DATE, orderInfo.getBuyTypeNum());
                    }
                }
                currdate = ca.getTime();
                long now = DateUtils.getUct8NowDate().getTime();
                if (currdate.getTime() < now) {
                    return false;
                }
                String enddate = format.format(currdate);
                System.out.println("增加天数以后的时间：" + enddate);
            } catch (ParseException e) {

            }

        }
        return true;
    }

    /**
     * 通过课程包名称和课程包id查询课程包
     *
     * @param coursePackageName 名称
     * @param coursePackageIds  课程包id列表
     * @return
     */
    public List<CoursePackage> selectByCoursePackageNameAndCourseIds(String coursePackageName, List<Integer> coursePackageIds) {
        if (coursePackageIds.size() == 0) {
            return new ArrayList<>();
        }
        List<CoursePackage> coursePackages = coursePackageMapper.selectByCoursePackageNameAndCoursePackageIds(coursePackageName, coursePackageIds);
        return coursePackages;
    }


    /**
     * 查询机构购买的所有项目
     *
     * @param projectName
     * @param trainOrganizationUserId 机构对应的用户id
     * @return
     */
    public List<ProjectInfo> selectByProjectNameAndTrainOrganizationUserId(String projectName, Integer trainOrganizationUserId) {
        return projectInfoMapper.selectByProjectNameAndTrainOrganizationUserId(projectName, trainOrganizationUserId);
    }

    /**
     * 查询机构购买的所有课程id
     *
     * @param trainOrganizationUserId
     * @return
     */
    public List<Integer> selectCourseIdsByTrainOrganizationUserId(Integer trainOrganizationUserId) {
        List<Integer> courseIds = courseMapper.selectCourseIdsByTrainOrganizationUserId(trainOrganizationUserId);
        List<Integer> packageIds = courseMapper.selectPackageCourseIdsByTrainOrganizationUserId(trainOrganizationUserId);
        List<Integer> projectIds = courseMapper.selectProjectCourseIdsByTrainOrganizationUserId(trainOrganizationUserId);
        courseIds.addAll(packageIds);
        courseIds.addAll(projectIds);
        return courseIds;
    }

    /**
     * 通过课程名称和课程id查询课程
     *
     * @param courseName 名称
     * @param courseIds  课程id列表
     * @return
     */
    public List<Course> selectByCourseNameAndCourseIds(String courseName, Integer type, List<Integer> courseIds) {
        if (courseIds.size() == 0) {
            return new ArrayList<>();
        }
        return courseMapper.selectByCourseNameAndIds(courseName, type, courseIds);
    }


    /**
     * 查询学员考试信息列表
     *
     * @param studentId
     * @return
     */
    public PageInfo<StudentExamVo> selectExamByStudentId(String name, Integer studentId, Integer type) {
//        List<StudentExamVo> exams = examMapper.selectExamByStudentIdAndDate(name, studentId);
//        PageInfo<StudentExamVo> pageInfo = new PageInfo<>(exams);
//        PageInfo<StudentExamVo> pageInfo1 = BeanCopyUtils.copyBean(pageInfo, PageInfo.class);
        //       List<StudentExamVo> applyExams = exams.stream().filter(e -> e.getApplyStatus().equals(ApplyStatusEnum.SUCCESS.getValue())).collect(Collectors.toList());
        //企业组卷分配的考试可以直接考试
        if (type != null && type == 2) {
            List<StudentExamVo> exams = examMapper.selectExamByStudentIdAndDateNoBuy(name, studentId);
            PageInfo<StudentExamVo> pageInfo = new PageInfo<>(exams);
            // PageInfo<StudentExamVo> pageInfo1 = BeanCopyUtils.copyBean(pageInfo, PageInfo.class);
            for (StudentExamVo studentExamVo : exams) {
                //企业组卷分配的考试可以直接考试
                if (studentExamVo.getTrainingOrganizationId() != null) {
                    studentExamVo.setMark(true);
                }
            }
            return pageInfo;
        }

        List<StudentExamVo> exams = examMapper.selectExamByStudentIdAndDateBuy(name, studentId);

        //必须该考试对应的课程包二级分类学时达到要求才能考试
        //通过学生id和考试id查询课程包分类id集合（二级分类）
        for (StudentExamVo studentExamVo : exams) {
            CourseCategoryExam courseCategoryExam = new CourseCategoryExam();
            courseCategoryExam.setExId(studentExamVo.getExamId());
            List<CourseCategoryExam> courseCategoryExamList = courseCategoryExamDao.queryAll(courseCategoryExam);
            if (courseCategoryExamList != null && courseCategoryExamList.size() > 0) {
                for (CourseCategoryExam item : courseCategoryExamList) {
                    //查询用户该分类下随堂考详情列表
                    List<CoursePackageQuizVo> list = studentQuizService.selectByCategoryIdAndStudentId(studentId, item.getCcId());
                    if (list != null && list.size() > 0) {
                        //统计学时
                        Double userClassHours = list.stream().mapToDouble(CoursePackageQuizVo::getClassHours).sum();
                        if (item.getClassHours() == null) {
                            item.setClassHours("0");
                        }
                        if (userClassHours >= Double.parseDouble(item.getClassHours())) {
                            studentExamVo.setMark(true);
                            break;
                        }
                    }
                }
            }
        }
//        List<StudentExamVo> examsQy = examMapper.selectExamByStudentIdAndDateNoBuy(name, studentId);
//        if (examsQy != null && examsQy.size() > 0) {
//            for (StudentExamVo studentExamVo : examsQy) {
//                //企业组卷分配的考试可以直接考试
//                if (studentExamVo.getTrainingOrganizationId() != null) {
//                    studentExamVo.setMark(true);
//                }
//            }
//            exams.addAll(examsQy);
//        }
//        List<StudentExamVo> result =  new ArrayList<>();
//        result.addAll(exams);
        PageInfo<StudentExamVo> pageInfo = new PageInfo<>(exams);
        return pageInfo;
    }

    //查找课程包包含的视频集合
    public List<Course> findCourse(List<CoursePackage> coursePackages) {
        List<Course> result = new ArrayList<>();
        for (CoursePackage coursePackage : coursePackages) {
            result.addAll(coursePackage.getRecordingCourses());
            if (!CollectionUtils.isEmpty(coursePackage.getCoursePackages())) {
                result.addAll(findCourse(coursePackage.getCoursePackages()));
            }
        }

        return result;
    }
}
